package com.qigao.mall.channel.weichat;

import com.alibaba.fastjson.JSONObject;
import com.qigao.mall.channel.ChannelCore;
import com.qigao.mall.channel.config.ChannelConstant;
import com.qigao.mall.commons.dto.MerChannelDto;
import com.qigao.mall.commons.enums.ChannelActionEnum;
import com.qigao.mall.commons.enums.ChannelCodeEnum;
import com.qigao.mall.commons.enums.ChannelInfoEnum;
import com.qigao.mall.commons.enums.PayProductEnum;
import com.qigao.mall.commons.param.ChannelReqParam;
import com.qigao.mall.commons.param.ChannelRespParam;
import com.qigao.mall.commons.utils.HttpClientUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * 微信H5 TOKEN检查
 */
@Service
public class WeichatOpenToken implements ChannelCore {
    private static Logger logger= LoggerFactory.getLogger(WeichatOpenToken.class);
    @Resource
    ChannelConstant channelConstant;

    @Override
    public boolean isSupport(PayProductEnum payProductEnum, ChannelActionEnum channelActionEnum, ChannelInfoEnum channelInfoEnum) {
        return ChannelActionEnum.CHECK_TOKEN.equals(channelActionEnum)
                &&
                PayProductEnum.WEICHAT_PC_LOGIN.equals(payProductEnum)
                &&
                ChannelInfoEnum.WEICHAT.equals(channelInfoEnum)
                ;
    }

    @Override
    public ChannelRespParam channelProcess(MerChannelDto merChannelDto, ChannelReqParam channelReqParam) {
        String checkTokenUrl=channelConstant.getWeichatOpenTokenUrl()+"?appid="+merChannelDto.getAppId()+"&secret="+merChannelDto.getAppSecret()+"&code="+channelReqParam.getReqContent()+"&grant_type=authorization_code";
        logger.info("[微信授权H5]请求地址:{}",checkTokenUrl);
        String respContent=HttpClientUtil.doGet(checkTokenUrl);
        logger.info("[微信授权H5]获取返回内容:{}",respContent);
        JSONObject respJson=JSONObject.parseObject(respContent);
        String errCode=respJson.getString("errcode");
        ChannelRespParam channelRespParam=new ChannelRespParam();
        channelRespParam.setRespCode(ChannelCodeEnum.SUCCESS.getCode());
        channelRespParam.setRespMsg(ChannelCodeEnum.SUCCESS.getName());
        if(errCode!=null&&!"0".equals(errCode)){
            channelRespParam.setRespCode(ChannelCodeEnum.FAIL.getCode());
            channelRespParam.setRespMsg(respJson.getString("errmsg"));
        }else {
            channelRespParam.setRespContent(respJson.toJSONString());
        }
        return channelRespParam;
    }
}
